/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.gateway.core.http.impl;

import info.peigen.hotpot.component.gateway.core.exception.GatewayBusinessException;
import info.peigen.hotpot.component.gateway.core.http.HttpClient;
import info.peigen.hotpot.component.gateway.core.http.enums.HttpType;
import info.peigen.hotpot.component.gateway.core.http.request.HttpRequest;
import info.peigen.hotpot.component.gateway.core.http.ssl.SslSocketHttpClientBase;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.noear.solon.annotation.Component;

import java.net.SocketTimeoutException;

/**
 * <b>(JsonHttpClient)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2019-05-28
 */
@Slf4j
@Component
public class JsonHttpClient extends SslSocketHttpClientBase implements HttpClient {

    public static final Integer CONNECT_TIMEOUT = 1;
    public static final Integer READ_TIMEOUT    = 4000;

    @Override
    public String send(HttpRequest request) throws Exception {
        switch (request.getMethodType()) {
            case GET:
                return doGet(request);
            case POST:
                return doPost(request);
            default:
                log.warn("请求异常：没找到正确的请求方式[默认POST]，HttpRequest={}", request);
                return null;
        }

    }

    private String doGet(HttpRequest req) throws Exception {
        OkHttpClient client = initClient(req);

        HttpUrl.Builder urlBuilder = HttpUrl.parse(req.getRequestUrl()).newBuilder();

        // 循环，把request.getRequestMessageMap()中的内容组合成入参
        req.getRequestMessageMap().entrySet().stream()
                .forEach(map -> urlBuilder.addQueryParameter(map.getKey(), map.getValue()));

        Request request = new Request.Builder().url(urlBuilder.build()).build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        } catch (Exception e) {
            if (e instanceof SocketTimeoutException) {
                throw e;
            }

            throw new GatewayBusinessException(e.getMessage(), e.getCause());
        }
    }

    private String doPost(HttpRequest req) throws Exception {
        OkHttpClient client = initClient(req);

        String      json     = com.alibaba.fastjson2.JSON.toJSONString(req.getRequestMessageMap());
        RequestBody formBody = RequestBody.create(JSON, json);

        Request request = new Request.Builder()
                .url(req.getRequestUrl())
                .addHeader("Content-Type", "application/json")
                .post(formBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        } catch (Exception e) {
            if (e instanceof SocketTimeoutException) {
                throw e;
            }

            throw new GatewayBusinessException(e.getMessage(), e.getCause());
        }
    }

    @Override
    public HttpType httpType() {
        return HttpType.JSON;
    }

}